package bosc.cn.service.transaction.impl;

import bosc.cn.dto.common.CommonResponse;
import bosc.cn.dto.common.ResponseWrapper;
import bosc.cn.service.transaction.TransactionStatusService;
import bosc.cn.service.transaction.bo.TransactionStatusReqBO;
import bosc.cn.service.transaction.bo.TransactionStatusResBO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import mapper.BusinessInfoMapper;
import model.BusinessInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@Slf4j
public class TransactionStatusServiceImpl implements TransactionStatusService {

    @Autowired
    private BusinessInfoMapper businessInfoMapper;

    @Override
    public ResponseWrapper<TransactionStatusResBO> queryTransactionStatus(TransactionStatusReqBO reqBO) {

        ResponseWrapper<TransactionStatusResBO> resBO = new ResponseWrapper<>();
        CommonResponse head = new CommonResponse();
        TransactionStatusResBO body = new TransactionStatusResBO();

        try {
            // 正常通信
            head.setRetCd("000000");
            head.setRetMsg("通信成功");
            head.setRetTm(LocalDateTime.now());

            // 原消费方流水号校验
            if (reqBO.getOriCnsmrSrlNo() == null || reqBO.getOriCnsmrSrlNo().trim().isEmpty()) {
                body.setPrcSts("PR99");
                body.setPrcMsg("原消费方流水号不能为空");
                resBO.setHead(head);
                resBO.setBody(body);
                return resBO;
            }

            BusinessInfo businessInfo = businessInfoMapper.selectOne(
                    new LambdaQueryWrapper<BusinessInfo>()
                            .eq(BusinessInfo::getCnsmrSrlNo, reqBO.getOriCnsmrSrlNo())
            );

            if (businessInfo == null) {
                body.setPrcSts("PR88");
                body.setPrcMsg("未找到该流水号对应的交易记录");
                resBO.setHead(head);
                resBO.setBody(body);
                return resBO;
            }

            // 查询到交易流水，返回交易状态
            body.setPrcSts("PR00");
            body.setPrcMsg("查询成功");
            body.setTxnSts(businessInfo.getTxnSts());

        } catch (Exception e) {
            // 出现异常，通信失败
            head.setRetCd("999999");
            head.setRetMsg("系统异常：" + e.getMessage());
            head.setRetTm(LocalDateTime.now());
        }

        // 最终组装 head + body
        resBO.setHead(head);
        resBO.setBody(body);

        return resBO;
    }
}
